package com.hsogoo.avatar.serialization.jdk;

import java.io.*;

import com.hsogoo.avatar.serialization.Serializer;

/**
 * @Author huangsaigang
 * Created @2018/9/25.
 */
public class JdkSerializer implements Serializer {

    @Override
    public byte[] encode(Object obj) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try{
            ObjectOutputStream os = new ObjectOutputStream(bos);
            os.writeObject(obj);
            os.flush();
            os.close();
            return bos.toByteArray();
        }finally {
            bos.close();
        }
    }

    @Override
    public <T> T decode(byte[] buf, Class<T> type) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(buf);
        try{
            ObjectInputStream ois = new ObjectInputStream(bis);
            T result = (T)ois.readObject();
            return result;
        }catch (ClassNotFoundException e){
            return null;
        }finally {
            bis.close();
        }
    }
}
